import { useEffect, useImperativeHandle, useState, forwardRef, useContext } from "react";
import "./StoTable.scss";
import ConfigContext from "@/main";


/* 石头表格的Props类型定义 */
export interface StoTableProps {
  ref: any;
  data: Record<string, any>[];
  pageSize?: number;
  sortableKeys?: string[];
  formatter?: Record<string, (item: Object) => JSX.Element>;
  currentPage?: number;
}

/* 石头表格对外暴露的API类型定义 */
export interface StoTableApi {
  // 对外暴露翻页方法
  turnToPage: (n: number) => void;
}

/* 
定义一个可被捕获实例的函数式组件
forwardRef<对外暴露的API类型, Props类型>
*/

const StoTable = forwardRef<StoTableApi, StoTableProps>(
  (
    {
      data,
      pageSize = 10,
      sortableKeys,
      formatter = {},
      currentPage: _currentPage = 1,
    },
    ref
  ) => {
    /* ========== START ========== */

    const contextData = useContext(ConfigContext)

    // 翻页方法
    const [currentPage, setCurrentPage] = useState(_currentPage);
    const turnToPage = (n: number) => {
      setCurrentPage(n);
    };

    // 使用useImperativeHandle将API方法绑定到ref
    useImperativeHandle(ref, () => ({
      turnToPage,
    }));

    const [tableData, setTableData] = useState(
      data.slice((currentPage - 1) * pageSize, pageSize * currentPage)
    );
    const [sortFlag, setSortFlag] = useState(true);

    const sortByKey = (key: string) => {
      console.log("sortByKey", key);
      setTableData([
        ...tableData.sort((a, b) => {
          let ret = (sortFlag ? a[key] > b[key] : a[key] < b[key]) ? 1 : -1;
          setSortFlag(!sortFlag);
          return ret;
        }),
      ]);
    };

    /* 监听currentPage的变化 */
    useEffect(() => {
      console.log("currentPage变了", currentPage);
      setTableData(
        data.slice((currentPage - 1) * pageSize, pageSize * currentPage)
      );
    }, [currentPage, data]);

    /* 组件挂载 */
    useEffect(() => {
      console.log("ComponentDidMount");
    }, []);

    return (
      <>

        {/* <p>data:{JSON.stringify(data)}</p>
        <p>pageSize:{pageSize}</p>
        <p>sortableKeys:{sortableKeys}</p> */}

        <div className="sto-table-table-container">
          {/* 表头 */}
          <div className="thead table-row">
            {/* 
            <div className="table-cell">id</div>
            <div className="table-cell">name</div>
            <div className="table-cell">age</div>
            <div className="table-cell">gender</div> 
            */}

            {
              tableData.length
                ? Object.keys(tableData[0]).map((key) => (
                  <div
                    key={key}
                    onClick={
                      sortableKeys?.includes(key) ? () => sortByKey(key) : undefined
                    }
                    className="table-cell"
                  >
                    {/* { key } */}
                    {contextData ? contextData.i18n[key][contextData.config.lang] : key}
                  </div>
                ))
                : (
                  <div className="no-data">暂无数据</div>
                )
            }
          </div>

          {/* 表格行 */}
          {/* 
          <div className="table-row">
            <div className="table-cell">单元格</div>
            <div className="table-cell">单元格</div>
            <div className="table-cell">单元格</div>
            <div className="table-cell">单元格</div>
          </div> 
          */}
          {tableData.map((item, index) => (
            <div key={index} className="table-row">
              {Object.keys(item).map((key) => (
                <div key={key} className="table-cell">
                  {
                    // formatter中包含avatar字段吗？包含的渲染方式：不包含的渲染方式
                    !Object.keys(formatter).includes(key)
                      ? item[key]
                      : formatter[key](item)
                  }
                </div>
              ))}
            </div>
          ))}
        </div>
      </>
    )

  }
);

export default StoTable;
